package jaeger

import (
	"encoding/json"
	streamCtx "gluenet/internal/glue-datasyncer/context"
	"gluenet/pkg/agent"
	corev1 "gluenet/pkg/agent/types"
	"gluenet/pkg/agent/v2/rpc"
	apis2 "gluenet/pkg/apis"
	"io"
	"net/http"
	"net/url"
)

const (
	DEFAULT_RPC_CONFIG = "nats://39.101.140.145:4222"
	DEFAULT_TEST_URL   = "http://39.101.140.145:30000/apis/instance/jaeger/proxy"
	TEST_TOKEN         = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJvd25lciI6IiIsIm5hbWUiOiIiLCJjcmVhdGVkVGltZSI6IiIsInVwZGF0ZWRUaW1lIjoiIiwiaWQiOiJjNmI2ZDY2My0yYWYwLTQ2ODctODgxNS01ZTg4ZDc4YmY4NDgiLCJ0eXBlIjoiIiwicGFzc3dvcmQiOiIiLCJwYXNzd29yZFNhbHQiOiIiLCJkaXNwbGF5TmFtZSI6IiIsImF2YXRhciI6IiIsInBlcm1hbmVudEF2YXRhciI6IiIsImVtYWlsIjoiIiwicGhvbmUiOiIiLCJsb2NhdGlvbiI6IiIsImFkZHJlc3MiOm51bGwsImFmZmlsaWF0aW9uIjoiIiwidGl0bGUiOiIiLCJpZENhcmRUeXBlIjoiIiwiaWRDYXJkIjoiIiwiaG9tZXBhZ2UiOiIiLCJiaW8iOiIiLCJ0YWciOiIiLCJyZWdpb24iOiIiLCJsYW5ndWFnZSI6IiIsImdlbmRlciI6IiIsImJpcnRoZGF5IjoiIiwiZWR1Y2F0aW9uIjoiIiwic2NvcmUiOjAsImthcm1hIjowLCJyYW5raW5nIjowLCJpc0RlZmF1bHRBdmF0YXIiOmZhbHNlLCJpc09ubGluZSI6ZmFsc2UsImlzQWRtaW4iOnRydWUsImlzR2xvYmFsQWRtaW4iOmZhbHNlLCJpc0ZvcmJpZGRlbiI6ZmFsc2UsImlzRGVsZXRlZCI6ZmFsc2UsInNpZ251cEFwcGxpY2F0aW9uIjoiIiwiaGFzaCI6IiIsInByZUh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Temporarily set the url to default value：http://localhost:16688/api/traces
	//TODO Need to add a method to find agent guid through application guid
	var uri string
	var dstUrl string
	uri = "http://localhost:16686/api/traces"
	applicationGuid := c.WebContext.URLParam("guid")
	//Need to get the scheme and host of the URL of the corresponding agent,
	//meanwhile, remove the guid field from the URL and combine into a complete URL
	originString := c.WebContext.Request().URL.String()
	u, err := url.Parse(originString)
	if err != nil {
		c.Logger.Errorf("failed to parse url", err.Error())
		c.WebContext.JSON(apis2.ResponseReqErr(err, nil))
		return
	}
	urlQuery := u.Query()
	urlQuery.Del("guid")
	if len(urlQuery) > 0 {
		dstUrl = uri + "?" + urlQuery.Encode()
	} else {
		dstUrl = uri
	}
	//Get the agent guid from the corresponding application guid
	agentGuidReqUrl := DEFAULT_TEST_URL + "?" + "guid=" + applicationGuid
	req, err := http.NewRequest("GET", agentGuidReqUrl, nil)
	if err != nil {
		c.Logger.Errorf("failed to create request", err.Error())
		c.WebContext.JSON(apis2.ResponseReqErr(err, nil))
		return
	}
	req.Header.Add("token", TEST_TOKEN)
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		c.Logger.Errorf("failed to get agent guid", err.Error())
		c.WebContext.JSON(apis2.ResponseReqErr(err, nil))
		return
	}
	defer resp.Body.Close()
	agentInfoMap := make(map[string]interface{})
	body, _ := io.ReadAll(resp.Body)
	_ = json.Unmarshal(body, &agentInfoMap)
	agentGuid := (agentInfoMap["data"].(map[string]interface{}))[applicationGuid].(map[string]interface{})["agent"]
	//Call RPC to get the response
	cli, err := agent.NewAgent(&rpc.Config{
		Target:  agentGuid.(string),
		NatsUrl: DEFAULT_RPC_CONFIG,
	})
	if err != nil {
		c.Logger.Errorf("rpc url is empty", err.Error())
		c.WebContext.JSON(apis2.ResponseReqErr(err, nil))
		return
	}
	rlt, err := cli.Proxy().Get(&corev1.ProxyGet{HttpUrl: dstUrl})
	if err != nil {
		c.Logger.Errorf("failed to request rpc", err.Error())
		c.WebContext.JSON(apis2.ResponseReqErr(err, nil))
		return
	}
	c.WebContext.JSON(apis2.ResponseOK(string(rlt)))
}
